package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.MemberSetmeal;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    //从属性文件中读取要生成html对应的目录
    @Value("${out_put_path}")
    private String outPutPath;

    //新增套餐,同时关联检查组
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if (checkgroupIds!=null && checkgroupIds.length>0){
            //绑定检查组和套餐的关系
            setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }
        //将图片名称保存到redis
        savePic2Redis(setmeal.getImg());
        //当添加套餐后需要重新生成静态页面（套餐列表页面，套餐详情页面）
        generateMobileStaticHtml();
    }

    //删除套餐
    @Override
    public void delete(Integer id) {
        //首先要从中间表中删除套餐和检查组的关联
        setmealDao.deleteAssociation(id);
        //然后才能将套餐删除
        setmealDao.delete(id);
    }

    //编辑套餐信息
    @Override
    public void edit(Integer[] chegroupIds, Setmeal setmeal) {
        //更新套餐的基本信息
        setmealDao.edit(setmeal);
        //从中间表中删除和该套餐相关的检查组的信息
        setmealDao.deleteAssociation(setmeal.getId());
        ////重新绑定检查组和套餐的关系
        if (chegroupIds!=null && chegroupIds.length>0){
            setSetmealAndCheckGroup(setmeal.getId(),chegroupIds);
        }
        //将图片名称保存到redis
        savePic2Redis(setmeal.getImg());
        //当修改套餐后要重新生成静态界面（套餐列表页面，套餐详情界面）
        generateMobileStaticHtml();
    }

    //生成静态页面
    public void generateMobileStaticHtml(){
        //生成静态页面之前查询所需数据
        List<Setmeal> setmealList = setmealDao.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐详情静态页面(多个)
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("setmeal",setmealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",dataMap);
        }
    }

    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String,Object> dataMap = new HashMap<>();
        //为模板提供数据
        dataMap.put("setmealList",setmealList);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
    }

    //用于生成静态页面
    public void generateHtml(String templateName,String htmlPageName,Map<String,Object> dataMap){
        //1.获得配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //2.加载模板文件
        Writer out = null;
        try {
            //2.1获取模板对象
            Template template = configuration.getTemplate(templateName);
            //2.2构造输出流，通过输出流写到指定文件上
            out = new FileWriter(new File(outPutPath+"/"+htmlPageName));
            //2.3输出文件
            template.process(dataMap,out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //查询所有套餐
    @Override
    public List<Setmeal> finAll() {
        return setmealDao.findAll();
    }

    //根据ID查询套餐信息
    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    //根据套餐ID查询关联的检查组ID
    @Override
    public List<Integer> findCheckgroupIdsBySetmealId(Integer setmealId) {
        return setmealDao.findCheckgroupIdsBySetmealId(setmealId);
    }

    //查询套餐名和数量（预约占比）
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);

        Page<Setmeal> page = setmealDao.selectByCondition(queryString);

        PageResult result = new PageResult(page.getTotal(), page.getResult());

        return result;
    }

    //绑定检查组和套餐的关系
    private void setSetmealAndCheckGroup(Integer id,Integer[] checkgroupIds){
        for (Integer checkgroupId : checkgroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmeal_id",id);
            map.put("checkgroup_id",checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }

    //将图片名称保存到redis
    private void savePic2Redis(String pic){
        if (pic!=null) {
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
        }
    }


    @Override
    public List<MemberSetmeal> getAllSetmealByphoneNumber(String phoneNumber) {
        return setmealDao.getAllSetmealByphoneNumber(phoneNumber);
    }

    @Override
    public MemberSetmeal findResultByOrderDate(Date orderDate) {

        MemberSetmeal resultByOrderDate = setmealDao.findResultByOrderDate(orderDate);
        return resultByOrderDate;
    }
    @Override
    public List<Map<String,Object>> getOrderSetmealByMemberId(Map map) {
        /*map.forEach(new BiConsumer() {
            @Override
            public void accept(Object o, Object o2) {
                System.out.println(o);
                System.out.println(o2);
            }
        });*/
        //System.out.println(id);
        /*Integer memberId = (Integer) map.get("memberId");
        Integer orderId = (Integer) map.get("orderId");
        return  setmealDao.getOrderSetmealByMemberId(memberId,orderId,map);*/
        return  setmealDao.getOrderSetmealByMemberId(map);
    }
}
